<?php

namespace App\Admin\Metrics\Examples;

use App\Models\Order;
use Carbon\Carbon;
use Dcat\Admin\Widgets\Metrics\RadialBar;
use Illuminate\Http\Request;

class Orders extends RadialBar
{
    /**
     * 初始化卡片内容
     */
    protected function init()
    {
        parent::init();

        $this->title('订单');
        $this->height(400);
        $this->chartHeight(300);
        $this->chartLabels('完成订单');
        $this->dropdown([
            '7' => '近7天',
            '30' => '近一月',
            '365' => '近一年',
        ]);
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        $orderQuery = Order::query();

        // 安全地获取 option 参数并限制其取值范围
        $allowedOptions = ['7', '30', '365'];
        $option = in_array($request->get('option'), $allowedOptions) ? $request->get('option') : '7';

        // 匹配天数
        $days = match ($option) {
            '365' => 365,
            '30' => 30,
            '7' => 7,
            default => 7, // 兜底保护
        };

        // 构造基础查询条件
        $baseQuery = clone $orderQuery; // 克隆查询对象避免副作用
        $filteredQuery = $baseQuery->whereDate('created_at', '>=', Carbon::now()->subDays($days));

        // 获取各个状态的数量
        $stateCounts = (clone $filteredQuery)
            ->select('state')
            ->selectRaw('COUNT(*) as count')
            ->groupBy('state')
            ->pluck('count', 'state');

        // 初始化各状态数量（使用空合并运算符）
        $states = [
            Order::STATE_WAIT_PAY,
            Order::STATE_WAIT_USE,
            Order::STATE_USE_EXPIRE,
            Order::STATE_USED,
            Order::STATE_PAY_EXPIRE,
            Order::STATE_REFUNDING,
            Order::STATE_REFUNDED,
        ];

        $counts = [];
        foreach ($states as $state) {
            $counts[$state] = $stateCounts[$state] ?? 0;
        }

        // 提取变量便于后续使用
        $orderWaitPay = $counts[Order::STATE_WAIT_PAY];
        $orderWaitUse = $counts[Order::STATE_WAIT_USE];
        $orderUseExpire = $counts[Order::STATE_USE_EXPIRE];
        $orderUsed = $counts[Order::STATE_USED];
        $orderPayExpire = $counts[Order::STATE_PAY_EXPIRE];
        $orderRefunding = $counts[Order::STATE_REFUNDING];
        $orderRefunded = $counts[Order::STATE_REFUNDED];

        // 计算总订单数（注意这里要重新构造无 groupBy 的查询）
        $totalCount = (clone $filteredQuery)->count('id');
        // 卡片内容
        $this->withContent($totalCount);
        // 卡片底部
        $this->withFooter($orderWaitPay, $orderWaitUse, $orderUseExpire, $orderUsed, $orderPayExpire, $orderRefunding, $orderRefunded);
        // 图表数据
        $ratio = 0;
        if ($totalCount > 0) {
            $ratio = round($orderUsed / $totalCount, 2);
        }
        $this->withChart($ratio);
    }

    /**
     * 设置图表数据.
     *
     * @param int $data
     *
     * @return $this
     */
    public function withChart(int $data)
    {
        return $this->chart([
            'series' => [$data],
        ]);
    }

    /**
     * 卡片内容
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content)
    {
        return $this->content(
            <<<HTML
<div class="d-flex flex-column flex-wrap text-center">
    <h1 class="font-lg-2 mt-2 mb-0">{$content}</h1>
    <small>总订单</small>
</div>
HTML
        );
    }

    /**
     * 卡片底部内容
     *
     * @param $orderWaitPay
     * @param $orderWaitUse
     * @param $orderUseExpire
     * @param $orderUsed
     * @param $orderPayExpire
     * @param $orderRefunding
     * @param $orderRefunded
     *
     * @return $this
     */
    public function withFooter($orderWaitPay, $orderWaitUse, $orderUseExpire, $orderUsed, $orderPayExpire, $orderRefunding, $orderRefunded)
    {
        return $this->footer(
            <<<HTML
<div class="d-flex justify-content-between p-1" style="padding-top: 0!important;">
    <div class="text-center">
        <p>待支付</p>
        <span class="font-lg-1">{$orderWaitPay}</span>
    </div>
    <div class="text-center">
        <p>待使用</p>
        <span class="font-lg-1">{$orderWaitUse}</span>
    </div>
    <div class="text-center">
        <p>使用过期</p>
        <span class="font-lg-1">{$orderUseExpire}</span>
    </div>
    <div class="text-center">
        <p>已使用</p>
        <span class="font-lg-1">{$orderUsed}</span>
    </div>
    <div class="text-center">
        <p>支付过期</p>
        <span class="font-lg-1">{$orderPayExpire}</span>
    </div>
    <div class="text-center">
        <p>退款中</p>
        <span class="font-lg-1">{$orderRefunding}</span>
    </div>
    <div class="text-center">
        <p>已退款</p>
        <span class="font-lg-1">{$orderRefunded}</span>
    </div>
</div>
HTML
        );
    }
}
